package com.hs.srm.admin.modules.harmfulsubstance.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.harmfulsubstance.entity.EnvironCommitmentEntity;
import com.hs.srm.admin.modules.harmfulsubstance.service.EnvironCommitmentService;
import com.hs.srm.admin.modules.notice.service.NoticeMainInfoService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 环保承诺书
 *
 * @author ych
 * @since 2020-03-05 14:25:18
 */
@RestController
@RequestMapping("/environCommitment")
public class EnvironCommitmentController extends AbstractController {

    @Resource
    private EnvironCommitmentService environCommitmentService;

    @Autowired
    private VendorService vendorService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private NoticeMainInfoService noticeMainInfoService;

    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        PageUtils page = environCommitmentService.queryPage(params);
        List<EnvironCommitmentEntity> list = (List<EnvironCommitmentEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }

    @SysLog("新增环保承诺书")
    @PostMapping("/save")
    public R save(EnvironCommitmentEntity entity, HttpServletRequest request) throws ServletException, IOException {
        VendorInfoEntity vendor = vendorService.selectByVendorCode(this.getUser().getUsername());
        return environCommitmentService.save(entity, request, vendor.getSapCode(), vendor.getVendorName());
    }

    /**
     * 环保承诺书新增页面
     *
     * @return
     */
    @GetMapping("/addCommitment")
    public ModelAndView addCommitment() {
        ModelAndView modelAndView = new ModelAndView("modules/harmful/commitment_add");
        VendorInfoEntity vendorInfoEntity = vendorService.selectByVendorCode(this.getUser().getUsername());
        if (ObjectUtil.isNotNull(vendorInfoEntity)) {
            modelAndView.addObject("vendorCode", vendorInfoEntity.getSapCode());
            modelAndView.addObject("vendorName", vendorInfoEntity.getVendorName());
        }
        return modelAndView;
    }

    /**
     * 环保承诺书审核页面
     *
     * @param id
     * @return
     */
    @RequiresPermissions("commitment:audit")
    @GetMapping("/audit/{id}")
    public ModelAndView audit(@PathVariable("id") String id) {
        ModelAndView modelAndView = new ModelAndView("modules/harmful/commitment_audit");
        EnvironCommitmentEntity entity = environCommitmentService.selectById(id);

        //审核人
        String name = this.getUser().getName();
        entity.setReviewer(name);
        //将附件前的路径去掉及上传文件时添加的时间，返回文件名。例：/aaa/bb/asd_20201010121212.txt --> asd.txt
        entity.setAttach(entity.getAttach().substring(entity.getAttach().lastIndexOf("/") + 1));
        entity.setAttach(entity.getAttach().replaceAll("_\\d+", ""));
        modelAndView.addObject("entity", EntityUtils.valToTxt(entity));
        return modelAndView;
    }

    @SysLog("环保承诺书审核")
    @PostMapping("/saveAudit")
    public R saveAudit(EnvironCommitmentEntity entity) {
        //审核人
        entity.setReviewer(this.getUser().getName());
        //审核时间
        entity.setReviewDate(new Date());
        //审核结论-1，退回，则该环保承诺书无效
        if (entity.getConclusion() == -1) {
            entity.setValidStatus(-1);
        } else {
            entity.setValidStatus(1);
        }
        environCommitmentService.updateById(entity);
        //通知供应商
        SysUserEntity vendorUser = sysUserService.selectOne(new EntityWrapper<SysUserEntity>()
                .eq("username", entity.getVendorCode()));
        String content = "您的环保承诺书已审核 " + (entity.getConclusion() == -1 ? "退回" : "通过") + " ！";
        noticeMainInfoService.saveNotice(vendorUser.getUserId(), content);

        return R.ok();
    }

    /**
     * 根据id下载附件
     */
    @RequestMapping("/downloadFileById")
    public void downloadFileById(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        EnvironCommitmentEntity ec = environCommitmentService.selectById(id);
        File file = new File(this.fileUploadPath + ec.getAttach());
        FileUtils.fileDownload(file, request, response);
    }

    /**
     * 失效功能
     */
    @SysLog("环保承诺书设置失效")
    @RequestMapping("/lapse")
    public R changeValidStatus(@RequestParam(value = "pkIds[]") String[] pkIds) {
        List<EnvironCommitmentEntity> environCommitmentEntities = environCommitmentService.selectBatchIds(Arrays.asList(pkIds));
        environCommitmentEntities.forEach(item -> item.setValidStatus(EnvironCommitmentEntity.WUXIAO));
        boolean b = environCommitmentService.updateBatchById(environCommitmentEntities);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

}

